package com.ibiaoke.common.configs;

import com.alibaba.fastjson.JSONObject;
import com.ibiaoke.common.utils.HttpUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;


/**
 * Created by huhaichao on 2017/5/26.
 */

public class WeChatConfigs {

    private static Logger logger = Logger.getLogger(WeChatConfigs.class);
    private static String accessToken;
    private static String jsapiTicket;

    public static String getAccessToken() {
        if(StringUtils.isBlank(accessToken)){
            getAccessTokenFromWeChat();
            logger.error("微信token不存在，已重新获取");
        }
        return accessToken;
    }
    public static String getJsapiTicket() {
        if(StringUtils.isBlank(jsapiTicket)){
            getJsapiTicketFromWeChat();
            logger.error("微信jsapiTicket不存在，已重新获取");
        }
        return jsapiTicket;
    }

    public void update(){
        getAccessTokenFromWeChat();
        getJsapiTicketFromWeChat();
    }

    /**
     * 从微信服务器获取token
     */
    private static void getAccessTokenFromWeChat() {
        String url2 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + getAppID()
                + "&secret=" + getAppSecret();

        String res2 = HttpUtil.httpClientGet(url2);

        if (StringUtils.isNotBlank(res2)) {
            JSONObject jsonObj = JSONObject.parseObject(res2);
            if (jsonObj.containsKey("access_token")) {
                accessToken = jsonObj.getString("access_token");
            }
        }
    }

    private static void getJsapiTicketFromWeChat(){
        String jsapiUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + getAccessToken() + "&type=jsapi";
        String res2 =  HttpUtil.httpClientGet(jsapiUrl);
        if(StringUtils.isNotBlank(res2)) {
            JSONObject jsonObj = JSONObject.parseObject(res2);
            if(jsonObj.containsKey("ticket")){
                jsapiTicket=jsonObj.getString("ticket");
            }
        }
    }



    public static String getAppID() {
        return GlobalConfigs.getConfigure(GlobalConfigsKey.WeChat.APP_ID);
    }

    public static String getAppSecret() {
        return GlobalConfigs.getConfigure(GlobalConfigsKey.WeChat.APP_SECRET);
    }

    public static String getMchID() {
        return GlobalConfigs.getConfigure(GlobalConfigsKey.WeChat.MERCHANT_ID);
    }

    public static String getApiSecret() {
        return GlobalConfigs.getConfigure(GlobalConfigsKey.WeChat.API_SECRET);
    }

    /**
     * 小程序APPID
     */
    public static String getXcxAppId() {
        return GlobalConfigs.getConfigure(GlobalConfigsKey.WeChat.xcx_appid);
    }

    /**
     * 小程序Secret
     */
    public static String getXcxAppSecret() {
        return GlobalConfigs.getConfigure(GlobalConfigsKey.WeChat.xcx_secret);
    }

}
